<script setup lang="ts">
import { ref } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import IconifyIcon from "@iconify-icons/ep/cloudy";
import { downloadByUrl, deviceDetection } from "@pureadmin/utils";
import * as XLSX from 'xlsx';
// 声明 props 类型
export interface FormProps {
  formInline: {
    user: string;
    region: string;
    id: string;
    template_url: string;
    dataList: object;
    checkCond: object;
    export_field: object;
  };
}

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({ user: "", region: "",dataList:[[]] })
});

const newFormInline = ref(props.formInline);


// 以二进制读取文件
const readFile = (file: any) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (e: any) => {
      resolve(e.target.result);
    };
  });
};
const downTemplate = () => {
  downloadByUrl(newFormInline.value.template_url)
  // window.open(newFormInline.value.template_url, '_blank')
};

const handleChange: UploadProps["onChange"] = async (uploadFile) => {
  //上传的文件
  let file = uploadFile.raw;
  if (!file) return;
  //读取上传的excel中的数据
  let data: any = await readFile(file);
  let workbook = XLSX.read(data, { type: "binary" ,raw: true, cellDates: true, dateNF: "yyyy/mm/dd"});
  //这里拿的是excel中第一个sheet表的数据
  const worksheet = workbook.Sheets[workbook.SheetNames[0]];
  // 把数据转化为json格式
  data = XLSX.utils.sheet_to_json(worksheet);
// 为每个用户添加 isActive 属性
  newFormInline.value.dataList = markDuplicates(data);
  if(data.length==0){
    return message(`excel中没有数据`, { type: "warning" });
  }

  console.log("表格数据",data,newFormInline);
};

function markDuplicates(arr) {
  const seen = new Map();
  return arr.map(item => {
    // const value = `${item['国家']}:${item['商品属性']}`;
    // const isDuplicate = seen.has(value);
    // if(isDuplicate){
    //   return {'状态检查': '重复数据',...item};
    // }else{
    let txt = '数据检查正常';//checkCond://检查字段，stateList.value,logisticsList.value,goodsOptionList.value
    const findBi1 = newFormInline.value.checkCond[0].find(x=>x.value==item['原币']||x.label==item['原币'])
    const findBi2 = newFormInline.value.checkCond[0].find(x=>x.value==item['目的币']||x.label==item['目的币'])
    if(findBi1 == undefined){
      txt = '货币不存在';
    }else if(findBi2 == undefined){
      txt = '目的币不存在';
    // }else if(findGoodsOption == undefined){
    //   txt = '没有找到商品属性';
      // }else{
      //   seen.set(value, true);
    }
    return {'状态检查': txt,...item};
    // }
  });
}

import moment from 'moment';
import {message} from "@/utils/message";
const cellFormat= function(row, column) {
  var data = row[column.property]
  return data
}


</script>

<template>
  <el-form :model="newFormInline" label-width="80px" label-position="left">
    <el-form-item label="第一步:">
      <el-link type="primary" @click="downTemplate">下载模板</el-link>
    </el-form-item>
    <el-form-item label="第二步:">
      <el-upload :show-file-list="false" action="#" :auto-upload="false" accept=".xls,.csv,.xlsx" :on-change="handleChange" :multiple="false">
        <el-button type="primary" :icon="useRenderIcon(IconifyIcon)">导入数据(1M以内)</el-button>
      </el-upload>
    </el-form-item>

    <el-table v-if="newFormInline.dataList" :data="newFormInline.dataList" style="width: 100%" size="small">
      <template v-if="newFormInline.dataList.length>0" v-for="item in Object.keys(newFormInline.dataList[0])">
        <el-table-column v-if="item =='状态检查'" :label="状态检查">
          <template #default="{ row, $index }">
            <span v-if="row['状态检查'] =='数据检查正常'||row['状态检查'] =='ok'" style="color:green">{{row['状态检查']}}</span>
            <span v-else style="color:red">{{row['状态检查']}}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip :prop="item" :label="item" v-else-if="item !='ID'&&item !='状态检查'" :formatter="cellFormat" />
      </template>
    </el-table>
  </el-form>
</template>
